package cheme.ProcessEditor.Parts.Equations;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.gef.editpolicies.ComponentEditPolicy;
import org.eclipse.gef.requests.GroupRequest;

import cheme.ProcessModel.IChild;
import cheme.ProcessModel.Cmds.DeleteCmd;
import cheme.ProcessModel.Equations.EquationField;

public class ccc_PolicyEquationField extends ComponentEditPolicy
{
	/*@Override
	public Command getCommand(Request request)
	{
		
		 * Fields have a few important requests that they forward on to thier 
		 * parent. 
		 
		
		if(request instanceof CreateAfterRequest)
		{
			return getCreateAfterCmd((CreateAfterRequest)request);
		}
		
		return super.getCommand(request);
	}*/
	
/*	protected Command getCreateAfterCmd(CreateAfterRequest request)
	{
		
		 * Give my parent a chance to create a new me after me.
		 
		
		
		 * If the request originated with this policies host, no need to
		 * add it again.
		 
		
		if(!((CreateAfterRequest)request).getAfterList().contains(getHost()))
		{
			((CreateAfterRequest)request).addToAfterList(getHost());
		}
		
		return getHost().getParent().getCommand(request);
	}*/
	
	@Override
	protected Command getDeleteCommand(GroupRequest request)
	{
		CompoundCommand cmd = new CompoundCommand();
		
		/*
		 * If there is only one field left in the equation, delete the whole equation.
		 */
		if(getHost().getParent().getChildren().size() == 1)
		{
			return getHost().getParent().getCommand(request);
		}

		/*
		 * Don't delete me if I am the last equation text field, doing so would
		 * make adding further identifier tokens necessitate drag and drop rather 
		 * and preclude the option of direct editing. Simply remove the existing tokens text instead?
		 */
		
		if(eqTokenCount() == 1 && getHost().getModel() instanceof EquationField)
		{
			//cmd.add(new  SetModelTextCmd((ITextModel)getHost().getModel(), ""));
			return getHost().getParent().getCommand(request);
		}
		else
		{
			cmd.add(new  DeleteCmd((IChild)getHost().getModel()));
		}
		
		return cmd.unwrap();
	}
	
	private int eqTokenCount()
	{
		int count = 0;
		
		for(Object part : getHost().getParent().getChildren())
		{
			count += (((EditPart)part).getModel() instanceof EquationField) ? 1 : 0;
		}
		
		return count;
	}
}
